<?php

namespace App\Kits\Traits;

use DateTimeInterface;
use Illuminate\Database\Eloquent\Builder;
use Illuminate\Http\Request;

trait BaseModelTrait
{

    protected function serializeDate(DateTimeInterface $date)
    {
        return $date->format('Y-m-d H:i:s');
    }

    public function scopeTimeRange(Builder $builder, Request $request, string $key = 'created_at')
    {
        $start_time = $request->input('start_time');
        $end_time = $request->input('end_time');
        $builder->when(!is_null($start_time), function (Builder $builder) use ($start_time, $key) {
            $builder->where($key, '>=', $start_time);
        })->when(!is_null($end_time), function (Builder $builder) use ($end_time, $key) {
            $end_time = now()->setDateTimeFrom($end_time)->addDay();
            $builder->where($key, '<=', $end_time);
        });
    }

    public function scopeSort(Builder $builder, Request $request)
    {
        $sort = $request->input('sort');
        $builder->when($sort, function (Builder $q) use ($sort) {
            $q->orderBy(...explode(',', $sort));
        });
    }

    public function scopeLike(Builder $builder, Request $request, array $keys)
    {
        $keyword = $request->input('keyword', $request->input('blurry'));
        $builder->when($keyword && !empty($keys), function (Builder $q) use ($keyword, $keys) {
            foreach ($keys as $index => $key) {
                if ($index === 0) {
                    $q->where($key, 'like', "%{$keyword}%");
                } else {
                    $q->orWhere($key, 'like', "%{$keyword}%");
                }
            }
        });
    }

    public function scopeEquals(Builder $builder, $keys, $values)
    {
        if (empty($keys) || empty($values)) {
            return;
        }
        if (is_string($values)) {
            $values = explode(',', $values);
        }
        $builder->when(is_array($keys), function (Builder $q) use ($keys, $values) {
            foreach ($keys as $index => $key) {
                if ($index === 0) {
                    $q->whereIn($key, $values);
                } else {
                    $q->orWhereIn($key, $values);
                }
            }
        })->when(is_string($keys), function ($q) use ($keys, $values) {
            $q->whereIn($keys, $values);
        });
    }
}
